'use client';

import { Fragment, useState, useEffect as React_useEffect } from 'react';
import * as React from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { X, ZoomIn, ZoomOut, Download, FileText, Image as ImageIcon } from 'lucide-react';
import GlassButton from './GlassButton';

interface DocumentPreviewProps {
  isOpen: boolean;
  onClose: () => void;
  documentTitle: string;
  documentId: string;
  fileType: string;
  filePath?: string;
}

export default function DocumentPreview({
  isOpen,
  onClose,
  documentTitle,
  documentId,
  fileType,
  filePath,
}: DocumentPreviewProps) {
  const [zoom, setZoom] = useState(100);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [fileUrl, setFileUrl] = useState<string>('');

  const isImage = fileType.startsWith('image/');
  const isPDF = fileType === 'application/pdf';
  const isText = fileType.startsWith('text/');

  const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3301/api';
  
  // 获取文件并创建blob URL
  const loadFile = async () => {
    setLoading(true);
    setError('');
    
    try {
      const token = localStorage.getItem('access_token');
      const response = await fetch(`${API_BASE_URL}/documents/${documentId}/download`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        throw new Error(`下载失败: ${response.status}`);
      }
      
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      setFileUrl(url);
      setLoading(false);
    } catch (err: any) {
      console.error('加载文件失败:', err);
      setError(err.message || '文件加载失败');
      setLoading(false);
    }
  };

  // 当对话框打开时加载文件
  React.useEffect(() => {
    if (isOpen && documentId) {
      loadFile();
    }
    
    // 清理blob URL
    return () => {
      if (fileUrl) {
        URL.revokeObjectURL(fileUrl);
      }
    };
  }, [isOpen, documentId]);

  const handleZoomIn = () => {
    setZoom(prev => Math.min(prev + 25, 200));
  };

  const handleZoomOut = () => {
    setZoom(prev => Math.max(prev - 25, 50));
  };

  const handleDownload = async () => {
    try {
      const token = localStorage.getItem('access_token');
      const response = await fetch(`${API_BASE_URL}/documents/${documentId}/download`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) throw new Error('下载失败');
      
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = documentTitle;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } catch (err) {
      console.error('下载失败:', err);
    }
  };

  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog as="div" className="relative z-50" onClose={onClose}>
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/70 backdrop-blur-sm" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-[95vw] h-[90vh] transform overflow-hidden rounded-3xl bg-white/95 dark:bg-gray-900/95 backdrop-blur-xl border border-gray-200/40 dark:border-white/10 shadow-2xl transition-all flex flex-col">
                {/* Header */}
                <div className="flex items-center justify-between p-6 border-b border-gray-200/40 dark:border-white/10">
                  <div className="flex items-center gap-3">
                    <div className="p-2 rounded-xl bg-gradient-to-br from-blue-500/20 to-purple-500/20">
                      {isImage ? (
                        <ImageIcon className="h-6 w-6 text-blue-600 dark:text-blue-400" />
                      ) : (
                        <FileText className="h-6 w-6 text-blue-600 dark:text-blue-400" />
                      )}
                    </div>
                    <div>
                      <Dialog.Title className="text-xl font-bold text-gray-900 dark:text-white">
                        {documentTitle}
                      </Dialog.Title>
                      <p className="text-sm text-gray-600 dark:text-white/60">
                        {fileType}
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2">
                    {(isImage || isPDF) && (
                      <>
                        <button
                          onClick={handleZoomOut}
                          className="p-2 rounded-xl hover:bg-gray-100 dark:hover:bg-white/10 transition-colors"
                          title="缩小"
                        >
                          <ZoomOut className="h-5 w-5 text-gray-600 dark:text-white/70" />
                        </button>
                        <span className="text-sm font-medium text-gray-600 dark:text-white/70 min-w-[60px] text-center">
                          {zoom}%
                        </span>
                        <button
                          onClick={handleZoomIn}
                          className="p-2 rounded-xl hover:bg-gray-100 dark:hover:bg-white/10 transition-colors"
                          title="放大"
                        >
                          <ZoomIn className="h-5 w-5 text-gray-600 dark:text-white/70" />
                        </button>
                        <div className="w-px h-6 bg-gray-300 dark:bg-white/20 mx-2"></div>
                      </>
                    )}
                    <button
                      onClick={handleDownload}
                      className="p-2 rounded-xl hover:bg-gray-100 dark:hover:bg-white/10 transition-colors"
                      title="下载"
                    >
                      <Download className="h-5 w-5 text-gray-600 dark:text-white/70" />
                    </button>
                    <button
                      onClick={onClose}
                      className="p-2 rounded-xl hover:bg-gray-100 dark:hover:bg-white/10 transition-colors"
                      title="关闭"
                    >
                      <X className="h-5 w-5 text-gray-600 dark:text-white/70" />
                    </button>
                  </div>
                </div>

                {/* Content */}
                <div className="flex-1 overflow-auto bg-gray-50 dark:bg-gray-900/50">
                  {loading && (
                    <div className="flex items-center justify-center h-full">
                      <div className="text-center">
                        <div className="relative inline-block">
                          <div className="h-16 w-16 rounded-full border-4 border-blue-200 dark:border-blue-900"></div>
                          <div className="absolute top-0 h-16 w-16 rounded-full border-4 border-t-blue-600 dark:border-t-blue-400 animate-spin"></div>
                        </div>
                        <p className="mt-4 text-gray-600 dark:text-white/60">
                          加载中...
                        </p>
                      </div>
                    </div>
                  )}

                  {error && (
                    <div className="flex items-center justify-center h-full">
                      <div className="text-center">
                        <div className="text-red-500 text-6xl mb-4">⚠️</div>
                        <p className="text-gray-900 dark:text-white font-semibold mb-2">
                          预览失败
                        </p>
                        <p className="text-gray-600 dark:text-white/60 text-sm">
                          {error}
                        </p>
                      </div>
                    </div>
                  )}

                  {!loading && !error && fileUrl && (
                    <>
                      {isImage && (
                        <div className="flex items-center justify-center min-h-full p-6">
                          <img
                            src={fileUrl}
                            alt={documentTitle}
                            style={{ width: `${zoom}%`, maxWidth: 'none' }}
                            className="rounded-lg shadow-2xl"
                          />
                        </div>
                      )}

                      {isPDF && (
                        <div className="w-full h-full">
                          <object
                            data={fileUrl}
                            type="application/pdf"
                            width="100%"
                            height="100%"
                          >
                            <div className="flex items-center justify-center h-full p-12">
                              <div className="text-center">
                                <p className="text-gray-900 dark:text-white font-semibold mb-2">
                                  浏览器不支持 PDF 预览
                                </p>
                                <p className="text-gray-600 dark:text-white/60 text-sm mb-4">
                                  请点击下载按钮下载文件后查看
                                </p>
                                <GlassButton onClick={handleDownload} variant="primary">
                                  <Download className="h-5 w-5 mr-2" />
                                  下载文件
                                </GlassButton>
                              </div>
                            </div>
                          </object>
                        </div>
                      )}

                      {isText && (
                        <div className="w-full h-full p-6">
                          <iframe
                            src={fileUrl}
                            title={documentTitle}
                            className="w-full h-full min-h-[600px] bg-white dark:bg-gray-800 rounded-lg shadow-2xl"
                          />
                        </div>
                      )}

                      {!isImage && !isPDF && !isText && (
                        <div className="flex items-center justify-center min-h-full p-6">
                          <div className="text-center max-w-md">
                          <FileText className="h-24 w-24 text-gray-400 mx-auto mb-4" />
                          <p className="text-gray-900 dark:text-white font-semibold mb-2 text-lg">
                            {fileType.includes('word') || fileType.includes('document') ? 'Word 文档' :
                             fileType.includes('presentation') || fileType.includes('powerpoint') ? 'PowerPoint 文档' :
                             fileType.includes('excel') || fileType.includes('spreadsheet') ? 'Excel 文档' :
                             '此文件类型'}暂不支持在线预览
                          </p>
                          <p className="text-gray-600 dark:text-white/60 text-sm mb-6">
                            {fileType.includes('word') || fileType.includes('document') || 
                             fileType.includes('presentation') || fileType.includes('powerpoint') ||
                             fileType.includes('excel') || fileType.includes('spreadsheet') ? (
                              <>
                                <span className="block mb-2">💡 建议下载文件后使用本地软件查看</span>
                                <span className="block text-xs">这样可以保证完美的格式显示和更好的阅读体验</span>
                              </>
                            ) : (
                              <>当前仅支持预览：图片 (JPG, PNG, GIF, WebP)、PDF、文本文件</>
                            )}
                          </p>
                          <GlassButton onClick={handleDownload} variant="primary" size="lg">
                            <Download className="h-5 w-5 mr-2" />
                            下载到本地查看
                          </GlassButton>
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  );
}

